package com.chat.websocket;

import com.chat.entry.po.UserMessage;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;

import java.io.IOException;

@Slf4j
@Component
@RequiredArgsConstructor
public class ChatMessageHandler implements WebSocketHandler {
    private final WebSocketSessionManager sessionManager;

    /**
     * 建立连接后
     *
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        Integer userId = getUserId(session);

        sessionManager.addSession(userId, session);
        log.info("用户Id:{} 已连接 WebSocket", userId);
    }

    /**
     * 处理消息
     *
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        log.info("收到消息:{}", message.getPayload());

        session.sendMessage(new TextMessage("服务器收到：" + message.getPayload()));
    }

    /**
     * 处理错误
     *
     * @param session
     * @param exception
     * @throws Exception
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.error("Chat WebSocket 错误: {}", exception.getMessage());
    }

    /**
     * 连接关闭后
     *
     * @param session
     * @param closeStatus
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        // 断开连接时移除session
        Integer userId = getUserId(session);

        sessionManager.removeSession(userId);
        log.info("用户Id:{} 已断开连接 WebSocket", userId);
    }

    /**
     * 支持部分消息
     *
     * @return
     */
    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

    // 从url后去userId,例如/websocket/friend/1
    private Integer getUserId(WebSocketSession session) {
        String path = session.getUri().getPath();
        String userIdStr = path.substring(path.lastIndexOf("/") + 1);
        return Integer.valueOf(userIdStr);
    }

    public boolean sendTextContent(UserMessage userMessage) {
        WebSocketSession session = sessionManager.getSession(userMessage.getReceiverId());
        ObjectMapper objectMapper = new ObjectMapper();

        // 可选：设置时间格式，避免 LocalDateTime 序列化问题
        objectMapper.findAndRegisterModules();

        try {
            // 构造 JSON 消息
            String payload = objectMapper.writeValueAsString(userMessage);

            if (session != null && session.isOpen()) {
                // ✅ 对方在线，直接推送
                session.sendMessage(new TextMessage(payload));
                log.info("✅ 推送给用户 {} 成功: {}", userMessage.getReceiverId(), payload);
                return true;
            } else {
                log.info("ℹ️ 用户 {} 不在线，消息仅存数据库，不推送", userMessage.getReceiverId());
                return false;
            }
        } catch (JsonProcessingException e) {
            log.error("❌ 消息序列化失败: {}", e.getMessage(), e);
        } catch (IOException e) {
            log.error("❌ 推送消息失败: {}", e.getMessage(), e);
        } catch (Exception e) {
            log.error("❌ 未知异常: {}", e.getMessage(), e);
        }
        return false;
    }

}
